<?php
/**
 * @package company app
 */

defined('_JEXEC') or die;

define( 'COM_EASYGALLERY_DIR', 'images/easygallery');
define( 'COM_EASYGALLERY_BASE', JPATH_ROOT."/".COM_EASYGALLERY_DIR );

define( 'COM_EASYGALLERY_IMAGE_DIR', COM_EASYGALLERY_DIR.'/images/');
define( 'COM_EASYGALLERY_IMAGE_BASE', JPATH_ROOT."/".COM_EASYGALLERY_IMAGE_DIR );
define( 'COM_EASYGALLERY_IMAGE_BASEURL', "/" . str_replace(DIRECTORY_SEPARATOR, '/', COM_EASYGALLERY_IMAGE_DIR ));

// integrate with job 
JLoader::register("Upload", JPATH_SITE.'/components/com_easygallery/class.upload.php/class.upload.php');

JTable::addIncludePath(JPATH_ADMINISTRATOR.'/components/com_easygallery/tables');

/**
 * Registration controller class for Users.
 */
class PCompanyModelLogo extends JModelLegacy
{
   public function getLogo() {
      $user = PFactory::getMasterUser(); 
      $db = PFactory::getDbo(); 
      /* the user must be valid */
      if(!$user || $user->id <= 0) {
         $this->setError('您无权访问该资源');
         return false;
      }

      $query = "SELECT a.imageid, a.filename, a.image_x, a.image_y, b.x1, b.x2, b.y1, b.y2, b.imageid as logoimageid " . 
               " FROM #__easygallery_images AS a " . 
               " LEFT JOIN #__easygallery_avatar AS b ON b.imageid=a.imageid " . 
               " WHERE a.id = " . $user->id . 
               " AND a.approve = 'Y' " . 
               " AND a.filename LIKE 'logo.%' LIMIT 1"; 

      $db->setQuery($query); 
      $logo = $db->loadAssoc(); 
      if(!$logo) {
         return array(); 
      }

      $logo['filename'] = COM_EASYGALLERY_IMAGE_BASEURL.'/'.$user->id.'/' . $logo['filename']; 
      return $logo; 
   }

   public function uploadLogo() {

      $data = JRequest::get('post');
      $user = PFactory::getMasterUser(); 

      /* the user must be valid */
      if(!$user || $user->id <= 0) {
         $this->setError('您无权访问该资源');
         return false;
      }

      $files = JRequest::get('files');

      if(!empty($files['Filedata']['name'])) {
         $image_data = $files['Filedata'];
         $fileext = JFile::getExt($image_data['name']);
         $image_data['name'] = JApplication::stringURLSafe(JFile::stripExt($image_data['name'])) . "." . $fileext;
         $file_id = "logo"; 

         $target_path = JPath::clean(COM_EASYGALLERY_IMAGE_BASE.'/'.$user->id.'/');

         if(!JFolder::exists($target_path))
            JFolder::create($target_path);

         $handle = new Upload($image_data, 'zh_CN');
         if ($handle->uploaded) {
            $handle->allowed = array("image/*");
            $handle->file_src_name_body      = $file_id; // hard name
            $handle->file_overwrite = true; 
            $handle->file_auto_rename = false; 
            $handle->image_resize            = false;
            $handle->process($target_path);
            if (!$handle->processed) {
               $this->setError($handle->error);
               return false;
            }
            // set stats 
            $data['id'] = $user->id;
            $data['date'] = PFactory::getDate()->toUnix();
            $data['image_type'] = $handle->image_src_type;
            $data['filename'] = $handle->file_dst_name;
            $data['image_size'] = @filesize($handle->file_dst_pathname);
            $data['image_x'] = $handle->image_src_x;
            $data['image_y'] = $handle->image_src_y;

            $handle-> clean();
         }
         else {
            $this->setError($handle->error);
            return false;
         }
         //check target path' files,delete gz files
         $uploadedLoges=new DirectoryIterator($target_path);
         foreach ($uploadedLoges as $logos) {
            if($logos->isfile()){
               $pathname=$logos->getPathname();
               $logo_ext= pathinfo($logos,PATHINFO_EXTENSION);
               if($logo_ext !='gz') continue;
               if(!JFile::delete($pathname)) {
                  $this->setError('系统错误，请重试');;
                  return fasle;
               }
            }
         }
      } elseif (empty($data['imageid'])) {
         $this->setError('Please select an image.');
         return false;
      }

      $data['approve'] = "Y";

      $row = $this->getTable('Images');

      /* try to load existing entry if it matches. Ignore any errors  */
      $row->load(array('id'=>$user->id, 'filename'=>$data['filename']));

      // Bind the form fields to the hello table
      if (!$row->bind($data)) {
         $this->setError($this->_db->getErrorMsg());
         return false;
      }

      // Make sure the hello record is valid
      if (!$row->check()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
      }

      // Store the web link table to the database
      if (!$row->store()) {
         $this->setError($row->getErrorMsg());
         return false;
      }

      // after we update table, we need to remove all old logo entries
      $db = PFactory::getDbo();
      $query = "DELETE FROM #__easygallery_images WHERE id=". $user->id . " AND filename !=" . $db->quote($data['filename']);
      $db->setQuery($query);
      $db->execute();

      $query = 'DELETE FROM #__easygallery_avatar '.
               'WHERE id='.$user->id;
      $db->setQuery($query);
      $db->execute();

      return $row->imageid;
   }

   public function saveLogo() {
      $user = PFactory::getMasterUser(); 

      /* the user must be valid */
      if(!$user || $user->id <= 0) {
         $this->setError('您无权访问该资源');
         return false;
      }

      $db = PFactory::getDbo();
      $data = JRequest::get('post');

      // The data must have imageid 
      if(empty($data['imageid'])) {
         $this->setError("Please select an image.");
         return false;
      }

      $row = $this->getTable('Images');
      if(!$row->load($data['imageid'])) {
         $this->setError("Image doesn't exists");
         return false;
      }

      $image = COM_EASYGALLERY_IMAGE_BASE.'/'.$user->id.'/'.$row->filename;

      $x1 = $data['x1'];
      $x2 = $data['x2'] > $row->image_x ? $row->image_x : $data['x2'];
      $y1 = $data['y1'];
      $y2 = $data['y2'] > $row->image_y ? $row->image_y : $data['y2'];

      $target_path = JPath::clean(JPATH_ROOT.'/images/comprofiler/gallery/'.$user->id.'/');
      if(!JFolder::exists($target_path))
          JFolder::create($target_path);

      $handle = new Upload($image, 'zh_CN');
      if ($handle->uploaded) {
         $handle->image_crop = array($y1, $handle->image_src_x-$x2, $handle->image_src_y-$y2, $x1); //$data['x1'], $data['x2']); //, $data['y2'], $data['y1']); 
         $handle->image_ratio_crop      = true;
         $handle->process($target_path);
         if (!$handle->processed) {
             $this->setError($handle->error);
             return false;
         }
      }

      /* we need to resize to smaller file */
      $image = $handle->file_dst_pathname;
      $file_id = md5($user->id);

      //thumbnail creation:
      $handle = new Upload($image, 'zh_CN');
      if($handle->uploaded) {
         $handle->file_src_name_body      = $file_id;
         $handle->file_overwrite = true;
         $handle->file_auto_rename = false;
         //$handle->image_resize            = true;
         $handle->image_ratio_x           = true;
         $handle->image_y                 = 180; //biggest size of picture
         $handle->process($target_path);

         /* remove intermediate file */
         JFile::delete($image);
         if (!$handle->processed) {
             $this->setError($handle->error);
               return false;
         }

         /* directly update cb avatar field */
         $avatarlink = "gallery/" . $user->id . "/" . $handle->file_dst_name. "?".time(); 
         $query = "UPDATE #__comprofiler " . 
                  " SET avatar=" . $db->quote($avatarlink) . ", avatarapproved=1, lastupdatedate=UTC_TIMESTAMP() WHERE id=" . (int) $user->id;
         $db->setQuery($query);
         if($db->execute()) {
            // update cached avatar link
            $user->avatar = $avatarlink; 
         }
      }
      else {
         $this->setError($handle->error);
         return false;
      }

      $row = $this->getTable('Avatar');
      if(!$row->load($user->id)) {
         $row->id = $user->id;
         $row->getDbo()->insertObject($row->getTableName(), $row);
      }

      /* from user set  */
      // Bind the form fields to the hello table
      if (!$row->bind($data)) {
         $this->setError($this->_db->getErrorMsg());
         return false;
      }

      // Make sure the hello record is valid
      if (!$row->check()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
      }

      // Store the web link table to the database
      if (!$row->store()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
      }

      // Event Driven Cache/Object Caching - clear any cache related to affected tables 
      CacheHelper::triggerRemove($user->id, array('#__comprofiler'));

      return "/images/comprofiler/gallery/". $user->id . '/' . $handle->file_dst_name;
   }

}
